<template>
  <el-dialog
    title="编辑提货点"
    class="poiontdia"
    :append-to-body="true"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    :visible.sync="syncPointDialog"
    :before-close="handleClose"
    width="610px"
  >
    <el-form
      :model="privatePoint"
      :rules="pointRules"
      ref="ruleForm"
      label-width="100px"
      label-position="left"
    >
      <el-form-item
        label="选择提货点"
        required
        prop="type"
        class="poiontdia__form"
      >
        <div class="poiontdia__form--con">
          <el-radio v-model="privatePoint.type" :label="0"
            >自定义提货点</el-radio
          >
          <el-radio v-model="privatePoint.type" :label="1">菜鸟驿站</el-radio>
        </div>
      </el-form-item>
      <el-form-item
        label="提货点名称"
        required
        prop="name"
        class="poiontdia__form"
      >
        <div class="poiontdia__form--con">
          <el-input
            v-model.trim="privatePoint.name"
            maxLength="10"
            type="text"
          ></el-input>
        </div>
      </el-form-item>
      <el-form-item
        label="选择线路"
        required
        prop="lineId"
        class="poiontdia__form"
      >
        <div class="poiontdia__form--con">
          <el-select
            v-model="privatePoint.lineId"
            class="poiontdia__form--addblock"
            placeholder="请选择线路"
          >
            <el-option label="未分组线路" value="-1"> </el-option>
            <el-option
              v-for="item in lineLists"
              :key="item.lineId"
              :label="item.lineName"
              :value="item.lineId"
            >
            </el-option>
          </el-select>
        </div>
        <el-button
          class="poiontdia__form--addline"
          @click="syncLineDialog = true"
          type="text"
          >添加 +
        </el-button>
      </el-form-item>
      <el-form-item
        label="选择区域"
        required
        prop="communityId"
        class="poiontdia__form"
      >
        <div class="poiontdia__form--con">
          <el-select
            v-model="privatePoint.communityId"
            class="poiontdia__form--addblock"
            placeholder="请选择区域"
          >
            <el-option
              v-for="(item, idx) in communities"
              :key="idx"
              :label="item.communityName"
              :value="item.communityId"
            >
            </el-option>
          </el-select>
        </div>
        <el-button
          class="poiontdia__form--addline"
          @click="pointAreaDialog = true"
          type="text"
          >添加 +
        </el-button>
      </el-form-item>
      <el-form-item
        label="地图定位"
        required
        prop="lngLat"
        class="poiontdia__form"
      >
        <div class="poiontdia__form--con poiontdia__form--mapbox">
          <el-amap-search-box
            ref="refAmapSearch"
            class="poiontdia__form--searchmap"
            :search-option="searchOption"
            :on-search-result="onSearchResults"
          >
          </el-amap-search-box>
          <el-amap
            ref="pointDialogAmap"
            vid="pointDialogAmap"
            :center="markers.position"
            :isHotspot="true"
            :zoom="12"
            :events="amapEvents"
            class="amap-demo"
          >
            <el-amap-marker
              :position="markers.position"
              :events="markers.events"
              :visible="markers.visible"
              :draggable="markers.draggable"
            >
            </el-amap-marker>
          </el-amap>
        </div>
      </el-form-item>
      <el-form-item
        label="联系人姓名"
        required
        prop="author"
        class="poiontdia__form"
      >
        <div class="poiontdia__form--con">
          <el-input v-model.trim="privatePoint.author" maxLength="6"></el-input>
        </div>
      </el-form-item>
      <el-form-item
        label="联系电话"
        required
        prop="phone"
        class="poiontdia__form"
      >
        <div class="poiontdia__form--con">
          <el-input v-model="privatePoint.phone" maxLength="11"></el-input>
        </div>
      </el-form-item>
      <el-form-item
        label="提货点照片"
        required
        prop="img"
        class="poiontdia__form"
      >
        <div class="poiontdia__form--con">
          <el-upload
            action=""
            ref="uploadFile"
            :auto-upload="true"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :http-request="uploadImage"
            :file-list="imageList"
            :on-success="uploadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :modal="false" :visible.sync="previewDialog">
            <img width="100%" :src="previewImgUrl" alt="" />
          </el-dialog>
        </div>
      </el-form-item>
    </el-form>

    <div class="poiontdia__footer">
      <el-button
        @click="
          handleClose(() => {
            syncPointDialog = false;
          })
        "
        >取 消</el-button
      >
      <el-button type="primary" @click="savaData">确 定</el-button>
    </div>

    <PointAreaDialog
      :pointAreaDialog.sync="pointAreaDialog"
      @savePointAreaDate="savePointAreaDate"
    >
    </PointAreaDialog>
  </el-dialog>
</template>

<script lang="ts">
import address from "@/views/goods/common/city.js";
import { upLoad } from "@/api/index";
import {
  Vue,
  Component,
  Prop,
  Emit,
  Watch,
  PropSync,
  Ref,
} from "vue-property-decorator";
import PointAreaDialog from "./PointAreaDialog.vue";
import {
  getShipperPullDownCommunitys,
  getShipperPullDownLines,
  setShippingLineInfo,
  setShipperCommunities,
} from "@/api/rection/index";
// import AMap from "vue-amap";
import axios from "axios";
import { placeAround, getadCodBycityCode } from "@/api/regionSelect";

@Component({
  components: { PointAreaDialog },
})
export default class PointDialog extends Vue {
  /** 提货点弹框 */
  @PropSync("pointDialog", { type: Boolean, default: false })
  syncPointDialog: boolean;

  /** 添加线路弹框 */
  @PropSync("lineDialog", { type: Boolean, default: false })
  syncLineDialog: boolean;

  /** 暂存添加线路完成时的数组 */
  @Prop({
    default() {
      return [];
    },
  })
  stagingLines: any;

  @Ref("refAmapSearch")
  refRefAmapSearch;

  @Ref("ruleForm")
  refRuleForm;

  @Prop()
  pointData: any;

  privatePoint = {
    /** 租户id  */
    tenantId: "",
    /** 城市合伙人id  */
    userId: "",
    /** 提货点类型0=自定提货点，1=菜鸟驿站 */
    type: 0,
    /** 提货点名称 */
    name: "",
    /** 关联线路id */
    lineId: "-1",
    /** 关联线路名称 */
    lineName: "",
    /** 关联区域id */
    communityId: "",
    /** 关联区域名称 */
    communityName: "",
    /** 省id */
    provinceId: "",
    /** 省名称 */
    provinceName: "",
    /** 市id */
    cityId: "",
    /** 市名称 */
    cityName: "",
    /** 区id */
    districtId: "",
    /** 区名称 */
    districtName: "",
    /** 具体位置坐标，经度纬度 */
    lngLat: "",
    /** 联系人姓名 */
    author: "",
    /** 联系电话 */
    phone: "",
    /** 提货点图片，json数组 */
    img: [],
    /** 提货点id */
    pointId: "",
    /** 提货点详情地址 */
    address: "",
    /** 提货点关联团长id */
    pointUserId: "",
  };

  /** 图片列表 */
  imageList = [];

  /** 线路列表 */
  lineLists = [];

  /** 区域列表 */
  communities = [];

  addressProv = address.getProvince();

  addressCity = [];

  addressArea = [];

  previewDialog = false;

  previewImgUrl = "";

  pointAreaDialog = false;

  /** 地图属性 */
  pointDialogAmap: any;

  searchOption = {
    /** 初始化地图数据 */
    city: "杭州",
    citylimit: false,
  };

  markers = {
    /** 初始化地图数据 */
    position: [121.5273285, 31.21515044],
    events: {
      click: () => {
        console.log("click marker");
      },
      dragend: e => {
        this.markers[0].position = [e.lnglat.lng, e.lnglat.lat];
      },
    },
    visible: true,
    draggable: false,
  };

  /**
   * 检测电话号码
   */
  validatePhone = (rule, value, callback) => {
    const patrn = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
    if (value === "") {
      callback(new Error("请输入电话号码"));
    } else if (patrn.test(value)) {
      callback();
    } else {
      callback(new Error("手机号格式输入错误"));
    }
  };

  /** 校验规则 */
  pointRules = {
    name: [
      {
        required: true,
        message: "请输入提货点名称",
        trigger: ["blur", "change"],
      },
    ],
    phone: [{ validator: this.validatePhone, trigger: ["blur", "change"] }],
    author: [
      {
        required: true,
        message: "请输入联系人姓名",
        trigger: ["blur", "change"],
      },
    ],
    lineId: [
      { required: true, message: "请选择线路", trigger: ["blur", "change"] },
    ],
    communityId: [
      { required: true, message: "请选择区域", trigger: ["blur", "change"] },
    ],
    img: [
      {
        required: true,
        message: "请上传提货点照片",
        trigger: ["blur", "change"],
      },
    ],
    lngLat: [
      {
        required: true,
        message: "请在地图上定位地址",
        trigger: ["blur", "change"],
      },
    ],
  };

  @Emit("emitPointData")
  emitPointData(data) {
    return data;
  }

  @Watch("pointData", { immediate: true, deep: true })
  onSetUpChange(nval) {
    if (nval) {
      this.privatePoint = {
        ...this.privatePoint,
        ...JSON.parse(JSON.stringify(nval)),
      };
    }
    this.imageList = this.privatePoint.img;
    this.$nextTick(() => {
      /** 初始化地图 */
      if (this.privatePoint.lngLat) {
        this.placeAround(this.privatePoint.lngLat);
        this.markers.position = this.privatePoint.lngLat
          .split(",")
          .map(i => parseFloat(i));
        (this.$refs.refAmapSearch as any).keyword = this.privatePoint.address;
      }
    });
  }

  @Watch("syncPointDialog")
  pointDialogChange(val) {
    if (val) {
      this.lineLists = [];
      this.communities = [];
      this.getShipperPullDownLines();
      this.getShipperPullDownCommunitys();
    } else {
      this.refRuleForm.resetFields();
    }
  }

  /** 将最新添加的增加到选择列表 */
  @Watch("stagingLines", { immediate: true, deep: true })
  stagingLinesChange(val: any) {
    if (val.length) {
      const temp = val[val.length - 1];
      this.privatePoint.lineId = temp.lineId;
      this.lineLists.push(temp);
    }
  }

  /** 关闭弹窗前回调 */
  handleClose(done) {
    this.$confirm("确定要退出该页面? 退出后，未保存的信息将不会保留!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        done();
      })
      .catch(() => {
        console.log("取消了关闭弹窗");
      });
  }

  /** 地图初始化事件 */
  amapEvents = {
    init: o => {
      o.getCity(() => {
        console.log("地图初始化完成", o);
      });
    },
    click: e => {
      console.log("点击了地图", e);
      this.markers.position = [e.lnglat.lng, e.lnglat.lat];
      this.placeAround(`${e.lnglat.lng},${e.lnglat.lat}`).then(res => {
        const data = res[0];
        console.log("这是点击地图回调", data);
        (this.$refs.refAmapSearch as any).keyword = data.name || data.address;
        res[1].address = data.name || data.address;
      });
    },
  };

  /**
   * 搜索回调
   */
  onSearchResults(pois) {
    console.log("搜索回调值", pois);
    if (pois.length > 0) {
      const pos = pois[0];
      this.markers.position = [pos.lng, pos.lat];
      this.privatePoint.address = pos.name || pos.address;
      this.placeAround(`${pos.lng},${pos.lat}`);
    }
  }

  /**
   * 根据经纬度查询地址详情
   */
  placeAround(lngLat: string) {
    return new Promise((resolve, reject) => {
      placeAround(lngLat)
        .then(res => {
          if (res.status === 200) {
            const data = res.data.pois;
            if (data.length) {
              const pro = this.privatePoint;
              const pos = data[0];
              getadCodBycityCode(`${pos.citycode}`).then(d => {
                this.privatePoint = {
                  ...pro,
                  provinceId: pos.pcode,
                  provinceName: pos.pname,
                  cityId: d,
                  cityName: pos.cityname,
                  districtId: pos.adcode,
                  districtName: pos.adname,
                  lngLat,
                };
                this.$nextTick(() => {
                  this.refRuleForm.validateField("lngLat");
                });
              });
              resolve([pos, this.privatePoint]);
            }
          }
        })
        .catch(err => {
          reject(err);
          this.$message.error("高德地图服务出错，请稍后重试!");
        });
    });
  }

  /**
   * 描述 编辑订单数
   * @param {any} idx: 序列号
   */
  editOrderNumItem(idx) {
    this.privateSetUp.orderNum.splice(idx, 1);
  }

  /**
   * 描述 新增订单数
   */
  addOrderNumItem() {
    const length = this.privateSetUp.orderNum.length;
    const temp = this.privateSetUp.orderNum[length - 1];
    if (!temp.num[1] || !temp.money) {
      this.$message.error("请将上条填写完整");
      return false;
    }
    if (length === 20) {
      this.$message.error("最多添加20条");
      return false;
    }
    this.privateSetUp.orderNum.push({
      num: [temp.num[1] + 1, temp.num[1] + 100],
      money: temp.money + 1,
    });
  }

  /**
   * 文件处理
   */
  beforeUpload(file) {
    const checkList = ["image/jpeg", "image/gif", "image/png"];
    const checkFlag = checkList.includes(file.type);
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!checkFlag) {
      this.$message.error("上传图片只支持 JPG或PNG 格式!");
      return false;
    }
    if (!isLt2M) {
      this.$message.error("上传图片大小不能超过 10MB!");
      return false;
    }
    return true;
  }

  /**
   * 描述 文件上传
   */
  async uploadImage(file) {
    const res = await upLoad({
      file: file.file,
    });
    return res;
  }

  /**
   * 描述 文件上传完成
   */
  uploadSuccess(res, file, files) {
    file.res = res;
    this.resetImgList(files);
    this.refRuleForm.clearValidate("img");
  }

  /**
   * 删除图片
   */
  handleRemove(file, files) {
    this.resetImgList(files);
  }

  /**
   * 图片预览
   */
  handlePictureCardPreview(file) {
    this.previewImgUrl = file.url;
    this.previewDialog = true;
  }

  /**
   * 更新图片数组
   */
  resetImgList(files) {
    const list = [];

    files.forEach(e => {
      if (e.res) {
        list.push({
          name: e.res.data,
          url: e.res.data,
        });
      } else {
        list.push({
          name: e.name,
          url: e.url,
        });
      }
    });
    this.privatePoint.img = list;
  }

  /**
   * 提货点管理-获取线路下拉
   */
  getShipperPullDownLines() {
    const params = {
      /** 租户id  */
      tenantId: "",
      /** 城市合伙人id  */
      userId: "",
    };
    getShipperPullDownLines(params)
      .then(res => {
        if (res.code === 200) {
          this.lineLists = res.data;
        }
      })
      .catch(err => {
        this.$message.error(err.msg || "网络异常，请稍后重试");
      });
  }

  /**
   * 提货点管理-获取区域下拉框
   */
  getShipperPullDownCommunitys() {
    const params = {
      /** 租户id  */
      tenantId: "",
      /** 城市合伙人id  */
      userId: "",
    };
    getShipperPullDownCommunitys(params)
      .then(res => {
        if (res.code === 200) {
          this.communities = res.data;
        }
      })
      .catch(err => {
        this.$message.error(err.msg || "网络异常，请稍后重试");
      });
  }

  /**
   * 保存区域到零时暂存区
   */
  savePointAreaDate(data) {
    this.communities = [...this.communities, ...data];
    this.pointAreaDialog = false;
    this.privatePoint.communityId = data[0].communityId;
  }

  /**
   * 检测线路和区域是否想要保存
   */
  checkLineAndArea() {
    const p = this.privatePoint;
    const proList = [];
    if (/^temp_/g.test(p.lineId)) {
      const param = this.deepCopy(
        this.stagingLines.find(i => i.lineId === p.lineId),
      );
      param.lineId = "";
      proList.push(setShippingLineInfo(param));
    }
    if (/^temp_/g.test(p.communityId)) {
      const temp = this.communities.find(i => i.communityId === p.communityId);
      const param = {
        /** 租户id  */
        tenantId: "",
        /** 城市合伙人id  */
        userId: "",
        lists: [
          {
            communityId: "",
            communityName: temp.communityName,
          },
        ],
        delIds: [],
      };
      proList.push(setShipperCommunities(param));
    }
    return axios.all(proList);
  }

  /**
   * 利用JSON做深拷贝
   */
  deepCopy(data) {
    return JSON.parse(JSON.stringify(data));
  }

  /**
   * 将新增的ID赋值回去
   */
  reserPrivateDate(res, param) {
    const resId = res.length && res[0].data.id;
    if (res.length === 2) {
      param.lineId = resId;
      param.communityId = res[1].data.id;
    } else if (res.length === 1) {
      if (/^temp_/g.test(param.lineId)) {
        param.lineId = resId;
      } else {
        param.communityId = resId;
      }
    }
    param.img = param.img.map(i => i.url);
  }

  /**
   * 保存数据
   */
  @Emit("refreshDataList")
  savaData() {
    // 检测是否输入完成
    if (
      !this.privatePoint.address ||
      !(this.$refs.refAmapSearch as any).keyword
    ) {
      this.privatePoint.lngLat = "";
    }
    this.refRuleForm.validate(valid => {
      if (valid) {
        this.checkLineAndArea()
          .then(res => {
            const idx = res.findIndex(i => i.code !== 200);
            if (idx === -1) {
              const param = this.deepCopy(this.privatePoint);
              this.reserPrivateDate(res, param);
              this.emitPointData(param);
              this.syncPointDialog = false;
            }
          })
          .catch(() => {
            this.$message.error("网络异常，请稍后重试");
          });
      } else {
        return false;
      }
    });
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/logistics/pickPoint.scss";
</style>
